package kit.views;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

import kit.core.Core;
import kit.core.ShellException;
import kit.persistency.KitDB;

import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

public class RoundConclusionPanel extends KitPanel {
	private JLabel label_1;
	private JLabel lblPerConcludereIl;
	private JButton btnCaricaFileEntropia;

	public RoundConclusionPanel() {
		setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		add(panel, BorderLayout.SOUTH);

		JButton btnCaricaSecondaRisposta = new JButton("Carica risposta");
		btnCaricaSecondaRisposta.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Core core = Core.obtainSingleton();
				KitFrame frame = (KitFrame) SwingUtilities
						.getRoot(RoundConclusionPanel.this);

				File firstHalfFile = RoundConclusionPanel.this.showLoadDialog(
						"Carica la prima metà",
						"Sono necessari entrambe i file", frame);
				if (firstHalfFile == null) {
					return;
				}
				File secondHalfFile = RoundConclusionPanel.this.showLoadDialog(
						"Carica la seconda metà",
						"Sono necessari entrambe i file", frame);
				if (secondHalfFile == null) {
					return;
				}

				try {
					String decodedHashedAnswer = core.decode(
							firstHalfFile.getAbsolutePath(),
							secondHalfFile.getAbsolutePath());
					RoundConclusionPanel.this.getAnswerFilePathLabel().setText(
							firstHalfFile.getName() + " - "
									+ secondHalfFile.getName());
					KitDB db = new KitDB();
					for (String secret : db.getAnswers(core
							.getCurrentQuestion())) {
						if (core.checkAnswer(secret, decodedHashedAnswer)) {
							frame.getStatusLabel().setBorder(
									new LineBorder(Color.green, 3));
							JOptionPane.showMessageDialog(frame,
									"Risposta corretta.", "Successo",
									JOptionPane.INFORMATION_MESSAGE);
							frame.getStatusLabel()
									.setText(
											"Per concludere il round carica il file relativo all'entropia.");

							File entropyFile = null;
							while (entropyFile == null) {
								entropyFile = RoundConclusionPanel.this
										.showSaveDialog(
												"Salva il valore dell'entropia",
												"E' necessario compiere il salvataggio ora.",
												frame);
							}
							core.encode(
									Double.toString(core.calculateRoundEntropy()),
									entropyFile.getAbsoluteFile());
							RoundConclusionPanel.this.getEntropyFilePathLabel()
									.setText(entropyFile.getAbsolutePath());

							RoundConclusionPanel.this
									.getCaricaFileEntropiaBottone().setEnabled(
											true);
							return;
						}
					}
				} catch (Exception e) {
					/*RoundConclusionPanel.this.showErrorDialog(e.getMessage(),
							frame);
					e.printStackTrace();
					return;*/
				}

				core.getCurrentChallenge().fail();
				frame.getStatusLabel().setBorder(new LineBorder(Color.red, 3));

				JOptionPane.showMessageDialog(frame, "Risposta errata.",
						"Fallimento", JOptionPane.INFORMATION_MESSAGE);
				frame.getStatusLabel().setText(
						core.getCurrentChallenge().toString());
				String question = core.getCurrentQuestion();
				String answer = core.getCurrentAnswer();
				KitDB db = new KitDB();
//				if(!db.setAnswerExposed(question, answer, true, core.getCalc()))
//					System.err.println("Not setted");

				if (core.getCurrentChallenge().isMaxFailuresLimitReached()) {
					core.setAnswersExposed();
					JOptionPane.showMessageDialog(frame,
							"Mallet è qui tra noi!\nLe risposte utilizzate nella verifica sono state marcate come esposte.",
							"Fallimento definitivo",
							JOptionPane.INFORMATION_MESSAGE);
				}

				frame.getGeneraDomandaMenuItem().setEnabled(true);
				frame.getGeneraRispostaMenuItem().setEnabled(true);
			}

		});
		panel.add(btnCaricaSecondaRisposta);

		btnCaricaFileEntropia = new JButton("Carica file entropia");
		btnCaricaFileEntropia.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				KitFrame frame = (KitFrame) SwingUtilities
						.getRoot(RoundConclusionPanel.this);
				Core core = Core.obtainSingleton();
				File eFile = RoundConclusionPanel.this.showLoadDialog(
						"Carica il file contenente l'entropia",
						"File non caricato.", frame);
				if (eFile == null) {
					return;
				}

				try {
					double entropy = Double.parseDouble(core.decode(eFile.getAbsolutePath()));
					frame.getGeneraDomandaMenuItem().setEnabled(true);
					frame.getGeneraRispostaMenuItem().setEnabled(true);
					frame.getMntmConcludiRound().setEnabled(false);

					core.getCurrentChallenge().concludeRound(entropy);
					if (core.getCurrentChallenge().getEntropy() >= core
							.getCurrentChallenge().getEntropyLimit()) {
						JOptionPane.showMessageDialog(frame, String.format(
								"Certifico l'identità di %s!",
								core.getReceiverUID()), "Successo",
								JOptionPane.INFORMATION_MESSAGE);
						frame.getStatusLabel().setText(
								core.getCurrentChallenge().toString()+" - Verifica effettuata con successo.");
					}else{
						frame.getStatusLabel().setText(
								core.getCurrentChallenge().toString());
					}

				} catch (IOException | InterruptedException | ShellException e) {
					RoundConclusionPanel.this.showErrorDialog(e.getMessage(),
							frame);
				}
			}
		});
		btnCaricaFileEntropia.setEnabled(false);
		panel.add(btnCaricaFileEntropia);

		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new FormLayout(
				new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC, }, new RowSpec[] {
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC, }));

		JLabel lblRispostaPrimo = new JLabel("Risposta:");
		panel_1.add(lblRispostaPrimo, "2, 2");

		lblPerConcludereIl = new JLabel("Carica i file contenenti la risposta");
		lblPerConcludereIl.setFont(new Font("Dialog", Font.PLAIN, 12));
		panel_1.add(lblPerConcludereIl, "4, 2");

		JLabel label = new JLabel("File entropia:");
		panel_1.add(label, "2, 4");

		label_1 = new JLabel(
				"Il file sarà generato dopo aver caricato le due metà");
		label_1.setFont(new Font("Dialog", Font.PLAIN, 12));
		panel_1.add(label_1, "4, 4");

	}

	public JLabel getEntropyFilePathLabel() {
		return label_1;
	}

	public JLabel getAnswerFilePathLabel() {
		return lblPerConcludereIl;
	}

	public JButton getCaricaFileEntropiaBottone() {
		return btnCaricaFileEntropia;
	}
}
